<template>
  <div class="location-map">
    <!-- 地图工具栏 -->
    <div class="map-toolbar" v-if="showToolbar">
      <div class="toolbar-left">
        <el-button-group size="mini">
          <el-button :type="mapType === 'satellite' ? 'primary' : ''" @click="changeMapType('satellite')">
            <i class="el-icon-view"></i> 卫星
          </el-button>
          <el-button :type="mapType === 'roadmap' ? 'primary' : ''" @click="changeMapType('roadmap')">
            <i class="el-icon-map-location"></i> 地图
          </el-button>
        </el-button-group>
      </div>
      <div class="toolbar-right">
        <el-button-group size="mini">
          <el-button @click="zoomIn">
            <i class="el-icon-zoom-in"></i>
          </el-button>
          <el-button @click="zoomOut">
            <i class="el-icon-zoom-out"></i>
          </el-button>
          <el-button @click="resetView">
            <i class="el-icon-refresh-left"></i>
          </el-button>
        </el-button-group>
        <el-button size="mini" @click="toggleFullscreen" style="margin-left: 10px;">
          <i :class="isFullscreen ? 'el-icon-copy-document' : 'el-icon-full-screen'"></i>
        </el-button>
      </div>
    </div>

    <!-- 地图容器 -->
    <div 
      ref="mapContainer" 
      class="map-container" 
      :class="{ 'fullscreen': isFullscreen }"
      :style="{ height: mapHeight }"
    >
      <!-- 地图占位符 -->
      <div class="map-placeholder" v-if="!mapLoaded">
        <div class="placeholder-content">
          <i class="el-icon-loading" style="font-size: 32px; color: #409EFF;"></i>
          <p style="margin-top: 10px;">地图加载中...</p>
        </div>
      </div>

      <!-- 实际地图容器 -->
      <div 
        id="amap-container" 
        class="amap-container"
        :style="{ height: '100%', display: mapLoaded ? 'block' : 'none' }"
      ></div>

      <!-- 地图信息面板 -->
      <div class="map-info-panel" v-if="showInfoPanel && currentLocation">
        <div class="panel-header">
          <span>位置信息</span>
          <el-button type="text" size="mini" @click="showInfoPanel = false">
            <i class="el-icon-close"></i>
          </el-button>
        </div>
        <div class="panel-content">
          <div class="info-item">
            <span class="label">经度：</span>
            <span class="value">{{ currentLocation.longitude }}</span>
          </div>
          <div class="info-item">
            <span class="label">纬度：</span>
            <span class="value">{{ currentLocation.latitude }}</span>
          </div>
          <div class="info-item">
            <span class="label">地址：</span>
            <span class="value">{{ currentLocation.address || '解析中...' }}</span>
          </div>
          <div class="info-item" v-if="currentLocation.updateTime">
            <span class="label">更新时间：</span>
            <span class="value">{{ formatTime(currentLocation.updateTime) }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 轨迹控制面板 -->
    <div class="track-control-panel" v-if="showTrackControl && trackData && trackData.length > 0">
      <div class="control-header">
        <span>轨迹回放</span>
        <el-button type="text" size="mini" @click="showTrackControl = false">
          <i class="el-icon-close"></i>
        </el-button>
      </div>
      <div class="control-content">
        <div class="playback-controls">
          <el-button-group size="mini">
            <el-button @click="startPlayback" :disabled="isPlaying">
              <i class="el-icon-video-play"></i> 播放
            </el-button>
            <el-button @click="pausePlayback" :disabled="!isPlaying">
              <i class="el-icon-video-pause"></i> 暂停
            </el-button>
            <el-button @click="stopPlayback">
              <i class="el-icon-refresh-left"></i> 重置
            </el-button>
          </el-button-group>
        </div>
        <div class="playback-progress">
          <el-slider
            v-model="playbackProgress"
            :max="trackData.length - 1"
            :step="1"
            :show-tooltip="false"
            @change="onProgressChange"
          ></el-slider>
        </div>
        <div class="playback-info">
          <span>{{ playbackProgress + 1 }} / {{ trackData.length }}</span>
          <span style="float: right;">速度: {{ playbackSpeed }}x</span>
        </div>
        <div class="speed-control">
          <el-radio-group v-model="playbackSpeed" size="mini">
            <el-radio-button :label="0.5">0.5x</el-radio-button>
            <el-radio-button :label="1">1x</el-radio-button>
            <el-radio-button :label="2">2x</el-radio-button>
            <el-radio-button :label="4">4x</el-radio-button>
          </el-radio-group>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'LocationMap',
  props: {
    // 地图高度
    height: {
      type: String,
      default: '400px'
    },
    // 当前位置
    location: {
      type: Object,
      default: null
    },
    // 轨迹数据
    trackData: {
      type: Array,
      default: () => []
    },
    // 是否显示轨迹
    showTrack: {
      type: Boolean,
      default: false
    },
    // 是否显示工具栏
    showToolbar: {
      type: Boolean,
      default: true
    },
    // 地图缩放级别
    zoom: {
      type: Number,
      default: 15
    },
    // 地图中心点
    center: {
      type: Array,
      default: () => [116.397428, 39.90923] // 北京天安门
    }
  },
  data() {
    return {
      // 地图实例
      map: null,
      // 地图是否加载完成
      mapLoaded: false,
      // 地图类型
      mapType: 'roadmap',
      // 是否全屏
      isFullscreen: false,
      // 当前位置
      currentLocation: null,
      // 位置标记
      locationMarker: null,
      // 轨迹线
      trackPolyline: null,
      // 轨迹标记数组
      trackMarkers: [],
      // 是否显示信息面板
      showInfoPanel: false,
      // 是否显示轨迹控制面板
      showTrackControl: false,
      // 轨迹回放相关
      isPlaying: false,
      playbackProgress: 0,
      playbackSpeed: 1,
      playbackTimer: null,
      // 移动标记
      movingMarker: null
    };
  },
  computed: {
    mapHeight() {
      return this.isFullscreen ? '100vh' : this.height;
    }
  },
  watch: {
    location: {
      handler(newLocation) {
        if (newLocation && this.map) {
          this.updateLocation(newLocation);
        }
      },
      deep: true,
      immediate: true
    },
    trackData: {
      handler(newTrackData) {
        if (newTrackData && newTrackData.length > 0 && this.map) {
          this.updateTrack(newTrackData);
        }
      },
      deep: true,
      immediate: true
    },
    showTrack(newValue) {
      if (this.map) {
        if (newValue) {
          this.showTrackControl = true;
          this.displayTrack();
        } else {
          this.showTrackControl = false;
          this.hideTrack();
        }
      }
    }
  },
  mounted() {
    this.initMap();
  },
  beforeDestroy() {
    this.cleanup();
  },
  methods: {
    /** 初始化地图 */
    initMap() {
      // 这里应该初始化实际的地图组件（如高德地图）
      // 由于没有实际的地图API密钥，这里使用模拟实现
      setTimeout(() => {
        this.mapLoaded = true;
        this.createMockMap();
        this.$emit('map-loaded', this.map);
      }, 1000);
    },

    /** 创建模拟地图 */
    createMockMap() {
      // 模拟地图对象
      this.map = {
        setCenter: (center) => {
          console.log('设置地图中心:', center);
        },
        setZoom: (zoom) => {
          console.log('设置地图缩放:', zoom);
        },
        addMarker: (marker) => {
          console.log('添加标记:', marker);
        },
        removeMarker: (marker) => {
          console.log('移除标记:', marker);
        },
        addPolyline: (polyline) => {
          console.log('添加轨迹线:', polyline);
        },
        removePolyline: (polyline) => {
          console.log('移除轨迹线:', polyline);
        }
      };

      // 如果有初始位置，显示位置
      if (this.location) {
        this.updateLocation(this.location);
      }

      // 如果有轨迹数据，显示轨迹
      if (this.trackData && this.trackData.length > 0 && this.showTrack) {
        this.updateTrack(this.trackData);
      }
    },

    /** 更新位置 */
    updateLocation(location) {
      this.currentLocation = location;
      
      if (this.map) {
        // 设置地图中心
        this.map.setCenter([location.longitude, location.latitude]);
        
        // 添加或更新位置标记
        if (this.locationMarker) {
          this.map.removeMarker(this.locationMarker);
        }
        
        this.locationMarker = {
          position: [location.longitude, location.latitude],
          title: location.address || '当前位置',
          icon: 'location'
        };
        
        this.map.addMarker(this.locationMarker);
        
        // 显示信息面板
        this.showInfoPanel = true;
      }
    },

    /** 更新轨迹 */
    updateTrack(trackData) {
      if (!this.map || !trackData || trackData.length === 0) return;
      
      // 清除现有轨迹
      this.clearTrack();
      
      // 创建轨迹线
      const path = trackData.map(point => [point.longitude, point.latitude]);
      this.trackPolyline = {
        path: path,
        strokeColor: '#409EFF',
        strokeWeight: 3,
        strokeOpacity: 0.8
      };
      
      this.map.addPolyline(this.trackPolyline);
      
      // 添加起点和终点标记
      if (trackData.length > 0) {
        const startPoint = trackData[0];
        const endPoint = trackData[trackData.length - 1];
        
        const startMarker = {
          position: [startPoint.longitude, startPoint.latitude],
          title: '起点',
          icon: 'start'
        };
        
        const endMarker = {
          position: [endPoint.longitude, endPoint.latitude],
          title: '终点',
          icon: 'end'
        };
        
        this.trackMarkers.push(startMarker, endMarker);
        this.map.addMarker(startMarker);
        this.map.addMarker(endMarker);
      }
      
      // 调整地图视野以包含所有轨迹点
      this.fitTrackBounds();
    },

    /** 显示轨迹 */
    displayTrack() {
      if (this.trackData && this.trackData.length > 0) {
        this.updateTrack(this.trackData);
      }
    },

    /** 隐藏轨迹 */
    hideTrack() {
      this.clearTrack();
    },

    /** 清除轨迹 */
    clearTrack() {
      if (this.trackPolyline) {
        this.map.removePolyline(this.trackPolyline);
        this.trackPolyline = null;
      }
      
      this.trackMarkers.forEach(marker => {
        this.map.removeMarker(marker);
      });
      this.trackMarkers = [];
      
      if (this.movingMarker) {
        this.map.removeMarker(this.movingMarker);
        this.movingMarker = null;
      }
    },

    /** 调整地图视野以包含轨迹 */
    fitTrackBounds() {
      if (!this.trackData || this.trackData.length === 0) return;
      
      // 计算边界
      let minLng = this.trackData[0].longitude;
      let maxLng = this.trackData[0].longitude;
      let minLat = this.trackData[0].latitude;
      let maxLat = this.trackData[0].latitude;
      
      this.trackData.forEach(point => {
        minLng = Math.min(minLng, point.longitude);
        maxLng = Math.max(maxLng, point.longitude);
        minLat = Math.min(minLat, point.latitude);
        maxLat = Math.max(maxLat, point.latitude);
      });
      
      // 设置地图视野
      const center = [(minLng + maxLng) / 2, (minLat + maxLat) / 2];
      this.map.setCenter(center);
      
      console.log('调整地图视野:', { center, bounds: { minLng, maxLng, minLat, maxLat } });
    },

    /** 开始轨迹回放 */
    startPlayback() {
      if (!this.trackData || this.trackData.length === 0) return;
      
      this.isPlaying = true;
      
      // 创建移动标记
      if (!this.movingMarker) {
        const startPoint = this.trackData[this.playbackProgress];
        this.movingMarker = {
          position: [startPoint.longitude, startPoint.latitude],
          title: '当前位置',
          icon: 'moving'
        };
        this.map.addMarker(this.movingMarker);
      }
      
      // 开始播放
      this.playbackTimer = setInterval(() => {
        if (this.playbackProgress < this.trackData.length - 1) {
          this.playbackProgress++;
          const currentPoint = this.trackData[this.playbackProgress];
          
          // 更新移动标记位置
          this.movingMarker.position = [currentPoint.longitude, currentPoint.latitude];
          
          // 更新地图中心
          this.map.setCenter(this.movingMarker.position);
          
          this.$emit('playback-progress', {
            progress: this.playbackProgress,
            total: this.trackData.length,
            currentPoint: currentPoint
          });
        } else {
          this.pausePlayback();
        }
      }, 1000 / this.playbackSpeed);
    },

    /** 暂停轨迹回放 */
    pausePlayback() {
      this.isPlaying = false;
      if (this.playbackTimer) {
        clearInterval(this.playbackTimer);
        this.playbackTimer = null;
      }
    },

    /** 停止轨迹回放 */
    stopPlayback() {
      this.pausePlayback();
      this.playbackProgress = 0;
      
      if (this.movingMarker) {
        this.map.removeMarker(this.movingMarker);
        this.movingMarker = null;
      }
    },

    /** 进度变化处理 */
    onProgressChange(value) {
      if (this.trackData && this.trackData[value]) {
        const currentPoint = this.trackData[value];
        
        if (this.movingMarker) {
          this.movingMarker.position = [currentPoint.longitude, currentPoint.latitude];
          this.map.setCenter(this.movingMarker.position);
        }
        
        this.$emit('playback-progress', {
          progress: value,
          total: this.trackData.length,
          currentPoint: currentPoint
        });
      }
    },

    /** 改变地图类型 */
    changeMapType(type) {
      this.mapType = type;
      // 实际实现中应该调用地图API改变地图类型
      console.log('改变地图类型:', type);
    },

    /** 放大地图 */
    zoomIn() {
      if (this.map) {
        // 实际实现中应该调用地图API放大
        console.log('放大地图');
      }
    },

    /** 缩小地图 */
    zoomOut() {
      if (this.map) {
        // 实际实现中应该调用地图API缩小
        console.log('缩小地图');
      }
    },

    /** 重置视图 */
    resetView() {
      if (this.map) {
        if (this.currentLocation) {
          this.map.setCenter([this.currentLocation.longitude, this.currentLocation.latitude]);
        } else if (this.trackData && this.trackData.length > 0) {
          this.fitTrackBounds();
        } else {
          this.map.setCenter(this.center);
        }
        this.map.setZoom(this.zoom);
      }
    },

    /** 切换全屏 */
    toggleFullscreen() {
      this.isFullscreen = !this.isFullscreen;
      
      if (this.isFullscreen) {
        document.body.style.overflow = 'hidden';
      } else {
        document.body.style.overflow = '';
      }
      
      // 延迟调整地图大小
      this.$nextTick(() => {
        if (this.map && this.map.resize) {
          this.map.resize();
        }
      });
    },

    /** 格式化时间 */
    formatTime(time) {
      if (!time) return '';
      const date = new Date(time);
      return date.toLocaleString();
    },

    /** 清理资源 */
    cleanup() {
      this.pausePlayback();
      
      if (this.isFullscreen) {
        document.body.style.overflow = '';
      }
      
      if (this.map) {
        // 清理地图资源
        this.clearTrack();
        if (this.locationMarker) {
          this.map.removeMarker(this.locationMarker);
        }
      }
    }
  }
};
</script>

<style scoped>
.location-map {
  position: relative;
  width: 100%;
}

.map-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  background-color: #f5f7fa;
  border: 1px solid #dcdfe6;
  border-bottom: none;
}

.map-container {
  position: relative;
  width: 100%;
  border: 1px solid #dcdfe6;
}

.map-container.fullscreen {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  z-index: 9999;
  background: white;
}

.map-placeholder {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  background-color: #f5f7fa;
  color: #909399;
}

.placeholder-content {
  text-align: center;
}

.amap-container {
  width: 100%;
  height: 100%;
}

.map-info-panel {
  position: absolute;
  top: 10px;
  right: 10px;
  width: 250px;
  background: white;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  z-index: 1000;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 15px;
  border-bottom: 1px solid #ebeef5;
  font-weight: bold;
}

.panel-content {
  padding: 15px;
}

.info-item {
  display: flex;
  margin-bottom: 8px;
}

.info-item .label {
  font-weight: bold;
  color: #606266;
  width: 70px;
  flex-shrink: 0;
}

.info-item .value {
  color: #303133;
  flex: 1;
  word-break: break-all;
}

.track-control-panel {
  position: absolute;
  bottom: 10px;
  left: 10px;
  right: 10px;
  background: white;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  z-index: 1000;
}

.control-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 15px;
  border-bottom: 1px solid #ebeef5;
  font-weight: bold;
}

.control-content {
  padding: 15px;
}

.playback-controls {
  margin-bottom: 15px;
}

.playback-progress {
  margin-bottom: 10px;
}

.playback-info {
  margin-bottom: 10px;
  font-size: 12px;
  color: #606266;
}

.speed-control {
  text-align: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .map-toolbar {
    flex-direction: column;
    gap: 10px;
  }
  
  .map-info-panel {
    position: static;
    width: 100%;
    margin-bottom: 10px;
  }
  
  .track-control-panel {
    position: static;
    margin-top: 10px;
  }
}
</style>